/*
 * @Description: 应用入口
 * @Date: 2022-12-06 20:21:30
 * @Author: lizhiqiang
 */
import { useEffect, useState } from "react";
import { message } from "antd";
import { useRoutes, useLocation, useNavigate } from "react-router-dom";
import router from "./router";
import useStore from "@/store";
import { loadMenuTree } from "@/request/menu";
import { loadUserMsg, loadLoginUserRole } from '@/request/api';
import { storage } from "@/utils/tools"

const ToPage = () => {
  const navigateTo = useNavigate();
  useEffect(() => {
    navigateTo("/workplace", { replace: true });
  }, []);
  return <div></div>;
};

const ToLogin = () => {
  const navigateTo = useNavigate();
  useEffect(() => {
    message.warning("登录失效！");
    navigateTo("/login");
  }, []);
  return <div></div>;
};

const BeforeRouterEnter =() => {
  const outlet = useRoutes(router);
  //如果中台过来
  let cloudjsToken = localStorage.getItem("cloudjsToken")
  if(cloudjsToken){
    let tokenWithoutBearer = cloudjsToken.replace('Bearer ', '');
    localStorage.setItem("token",tokenWithoutBearer);
    loadUserMsg(tokenWithoutBearer)
  }
  let token = localStorage.getItem("token");
  if (location.pathname === "/login" && token) {
    // console.log('在登录有token')
    return <ToPage />;
  }

  if (location.pathname === "/" && token) {
    return <ToPage />;
  }
 
  sessionStorage.setItem("oldPath", sessionStorage.getItem("currentPath") || location.pathname);
  sessionStorage.setItem("currentPath", location.pathname);
  if(location.pathname !=="/login" && !token){
    return <ToLogin />
  }

  return outlet;
};

const App = () => {
  const location = useLocation();
  const setLogin = useStore((state) => state.setLogin);
  const login = useStore((state) => state.login);
  const setUserInfo = useStore((state) => state.setUserInfo);
  const setLoginUserRole = useStore((state) => state.setLoginUserRole);

  const getUrlParams = (url: string) => {
    // 通过 ? 分割获取后面的参数字符串
    let urlStr = url.split("?")[1];
    // 创建空对象存储参数
    let obj = {};
    // 再通过 & 将每一个参数单独分割出来
    let paramsArr = urlStr.split("&");
    for (let i = 0, len = paramsArr.length; i < len; i++) {
      // 再通过 = 将每一个参数分割为 key:value 的形式
      let arr = paramsArr[i].split("=");
      obj[arr[0]] = arr[1];
    }
    return obj;
  };

  const getUser = async () => {
    if (localStorage.getItem("token")) {
      const { code, data } = await loadUserMsg(localStorage.getItem("token"))
      if (code === 200) {
        setUserInfo(data || {})
      }
    }
  }
  const getUserRole = async () => {
    const token = localStorage.getItem("token")
    if (token) {
      const { code, data } = await loadLoginUserRole()
      if (code === 200) {
        setLoginUserRole(data || {})
      }
    }
  }
  useEffect(() => {
    if (location.pathname != "/workplace") {
      getUser();  //首页不调用
      // getUserRole();  //获取用户角色，注释
    }
  }, []);
  return (
    <div className="App">
      <BeforeRouterEnter />
    </div>
  );
};

export default App;
